// API请求封装
import { getApiBaseUrl } from './env'
import { handleError } from './errorHandler'
import { REQUEST_TIMEOUT } from '../constants/api';

// 获取基础URL
const baseURL = getApiBaseUrl();

/**
 * 创建带有超时的fetch请求
 * @param {string} url - 请求URL
 * @param {Object} options - 请求选项
 * @param {number} timeout - 超时时间（毫秒）
 * @returns {Promise} fetch Promise
 */
const fetchWithTimeout = (url, options = {}, timeout = REQUEST_TIMEOUT.DEFAULT) => {
  return Promise.race([
    fetch(url, options),
    new Promise((_, reject) => 
      setTimeout(() => reject(new Error('Request timeout')), timeout)
    )
  ])
}

/**
 * 通用请求处理函数
 * @param {string} url - 请求URL
 * @param {Object} options - 请求选项
 * @param {number} timeout - 超时时间
 * @returns {Promise} 响应数据
 */
const request = async (url, options = {}, timeout = REQUEST_TIMEOUT.DEFAULT) => {
  try {
    const fullUrl = `${getApiBaseUrl()}${url}`
    const defaultOptions = {
      headers: {
        'Content-Type': 'application/json',
      },
      ...options
    }
    
    const response = await fetchWithTimeout(fullUrl, defaultOptions, timeout)
    
    if (!response.ok) {
      const error = new Error(`HTTP error! status: ${response.status}`)
      error.response = { status: response.status }
      throw error
    }
    
    // 检查响应是否为JSON
    const contentType = response.headers.get('content-type')
    if (contentType && contentType.includes('application/json')) {
      return await response.json()
    }
    
    return await response.text()
  } catch (error) {
    console.error(`Request failed [${options.method || 'GET'}] ${url}:`, error)
    throw error
  }
}

/**
 * 封装GET请求
 * @param {string} url - 请求路径
 * @param {Object} params - 请求参数
 * @returns {Promise} - 返回Promise对象
 */
export const get = async (url, params = {}) => {
  try {
    // 构建查询字符串
    const queryString = Object.keys(params)
      .map(key => `${encodeURIComponent(key)}=${encodeURIComponent(params[key])}`)
      .join('&');
    
    // 拼接完整URL
    const fullUrl = `${url}${queryString ? `?${queryString}` : ''}`;
    
    return await request(fullUrl, { method: 'GET' })
  } catch (error) {
    handleError(error, `GET ${url}`)
    throw error
  }
};

/**
 * 封装POST请求
 * @param {string} url - 请求路径
 * @param {Object} data - 请求数据
 * @returns {Promise} 响应数据
 */
export const post = async (url, data = {}) => {
  try {
    return await request(url, {
      method: 'POST',
      body: JSON.stringify(data)
    })
  } catch (error) {
    handleError(error, `POST ${url}`)
    throw error
  }
}
/**
 * 封装PUT请求
 * @param {string} url - 请求路径
 * @param {Object} data - 请求数据
 * @returns {Promise} 响应数据
 */
export const put = async (url, data = {}) => {
  try {
    return await request(url, {
      method: 'PATCH',
      body: JSON.stringify(data)
    })
  } catch (error) {
    handleError(error, `PUT ${url}`)
    throw error
  }
}



/**
 * 封装DELETE请求
 * @param {string} url - 请求路径
 * @returns {Promise} 响应数据
 */
export const del = async (url) => {
  try {
    return await request(url, { method: 'DELETE' })
  } catch (error) {
    handleError(error, `DELETE ${url}`)
    throw error
  }
}

/**
 * 封装文件上传请求
 * @param {string} url - 请求路径
 * @param {FormData} formData - 表单数据
 * @returns {Promise} 响应数据
 */
export const upload = async (url, formData) => {
  try {
    const fullUrl = `${getApiBaseUrl()}${url}`
    
    // 使用更长的超时时间处理文件上传
    const response = await fetchWithTimeout(fullUrl, {
      method: 'POST',
      body: formData // 不设置Content-Type，让浏览器自动设置
    }, REQUEST_TIMEOUT.UPLOAD)
    
    if (!response.ok) {
      const error = new Error(`Upload failed: ${response.status}`)
      error.response = { status: response.status }
      throw error
    }
    
    return await response.json()
  } catch (error) {
    handleError(error, `UPLOAD ${url}`)
    throw error
  }
}

/**
 * 获取图片完整URL
 * @param {string} path - 图片路径
 * @returns {string} - 完整URL
 */
export const getImageUrl = (path) => {
  // 如果路径已经是完整URL或是本地导入的资源，则直接返回
  if (!path || path.startsWith('http') || path.startsWith('data:') || typeof path === 'object') {
    return path;
  }
  
  // 否则拼接基础URL和路径
  return `${baseURL}${path}`;
};

/**
 * 格式化URL，确保包含协议前缀
 * @param {string} url - 原始URL
 * @returns {string} - 格式化后的URL
 */
export const formatUrl = (url) => {
  if (!url) return '#';
  
  // 如果URL已经包含协议前缀，则直接返回
  if (url.startsWith('http://') || url.startsWith('https://')) {
    return url;
  }
  
  // 否则添加https://前缀
  return `https://${url}`;
};